<?php

namespace app\http\middleware;

use think\Config;

class Check
{
    public function handle($request, \Closure $next)
    {
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Credentials: true');
        header("Access-Control-Allow-Methods:*");
        header("Access-Control-Allow-Headers:Content-Type,Access-Token,X-Token");
        header("Access-Control-Expose-Headers:*");
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            exit;
        }
        define('ROOT_TOKEN','os2rftxaXgM0vWL1QzOH');
        $module = $request->module();//模块名
        $controller = $request->controller();//控制器名
        $action = $request->action();//方法名
        $is_except=in_array($module.'/'.$controller.'/'.$action,Config('except_check.'));

        if(!$is_except && $module!=='generate'){
            // --- 需要token访问的接口 ---
            $_data['token']=input('token');
            //获取token信息（account_id、expires_in、create_time、end_time）
            $data=get_curl('login','token/info',$_data);
            //判断token是否存在
            if($data['status']){
                $token=$data['data'];
                //定义 ACCOUNTID（类似session存id）
                define('ACCOUNTID',$token['account_id']);
                //角色及接口验证
                $admin_check = false;       //管理员
                $merchant_check = false;    //商家
                $user_check = false;        //用户

                //判断是否有后台管理员模块
                if (Config('except_check_admin.status')){
                    //查找account_id对应的管理员
                    $admin_user=get_curl('user','admin_user/info',['account_id'=>ACCOUNTID]);
                    if ($admin_user['status'] && $admin_user['data']['status']==1){
                        //检查禁止访问的接口
                        if(!in_array($module.'/'.$controller.'/'.$action,Config('except_check_admin.access_forbidden'))){
                            //检查当前访问的接口是否有权限
                            $have_permissions[] = in_array($module.'/'.$controller.'/'.$action,Config('except_check_admin.except_check_api'));
                            $have_permissions[] = in_array($module.'/'.$controller,Config('except_check_admin.except_check_controller'));
                            //特殊判断赋值
                            if ($module == 'login' && $controller=='Account'){
                                $module = 'user';
                                $controller = 'AdminUser';
                            } elseif ($module == 'shop_admin_auth' && $controller=='AdminRole'){
                                $module = 'user';
                                $controller = 'AdminUser';
                            } elseif ($module == 'shop_admin_auth' && ($controller=='ShopAdminPageRole' || $controller=='ShopAdminPageTree')){
                                $controller='AdminPage';
                            }
                            //获取管理员可访问的接口地址
                            $admin_page=get_curl('shop_admin_auth','admin_page/get_admin_page',['account_id'=>ACCOUNTID]);
                            $have_permissions[] = in_array($module.'/'.$controller,$admin_page['data']);

                            foreach ($have_permissions as $k=>$v){
                                if ($v){
                                    $admin_check = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                //判断是否有用户模块
                if (Config('except_check_user.status')){
                    //查找account_id对应的管理员
                    $admin_user=get_curl('user','user/info',['account_id'=>ACCOUNTID]);
                    if ($admin_user['status'] && $admin_user['data']['status']==1){

                    }



                }


                //判断是否有权限访问
                if(!$admin_check && !$merchant_check && !$user_check){
                    echo \tools\curl\Curl::arr2json(['status'=>false,'msg'=>'无权限访问']);
                    die;
                }
            }else{
                echo \tools\curl\Curl::arr2json(['status'=>false,'msg'=>'Token不可用']);
                //停止往后运行方法
                die;
            }
        }else{
            define('ACCOUNTID',null);
        }
        define('SYSSIGN', 'base');
        if (preg_match('~micromessenger~i', $request->header('user-agent'))) {
            $request->InApp = 'WeChat';
        } else if (preg_match('~alipay~i', $request->header('user-agent'))) {
            $request->InApp = 'Alipay';
        }
        if (SYSSIGN) {
            $request->sys_sign = SYSSIGN;
        }
        $pagesize=input('pagesize')?input('pagesize'):input('limit');
        if($pagesize){
            Config('paginate.list_rows',$pagesize);
        }
        return $next($request);
    }
}
